import toml from "@iarna/toml";
import jsonc from "jsonc";
import {copySync,emptyDirSync,ensureDirSync,removeSync,readFileSync,outputFileSync,readJsonSync,writeJSONSync} from "fs-extra";
import {globby} from "globby"

// 文件夹扫描
export const scan = (path,options) => {
    return globby(path,options)
}
// 文件夹文件递归处理的处理~ 

// 文件夹扫描，
// 文件读写，

// toml 读写，
export const readToml = (path,options={encoding:'utf8', flag:'r'}) => {
    if(!/\.toml$/.test(path)){
        throw new Error(`readToml :: 文件格式错误！ path = ${path}`)
    }
    const str = readFileSync(path,{encoding:'utf8', flag:'r'});
    //
    return toml.parse(str);
}

export const writeToml = (path,data,options) => {
    if(!/\.toml$/.test(path)){
        throw new Error(`readToml :: 文件格式错误！ path = ${path}`)
    }
    if(!data){
        throw new Error(`readToml :: 没有数据！ data = null | undefined`)
    }
    const s = toml.stringify(data);
    outputFileSync(path,s,options)
}
// json 读写
export const readJson = (path,options) => {
    if(!/.json$/.test(path)){
        throw new Error(`readJson :: 文件格式错误！ path = ${path}`)
    }
    //
    return readJsonSync(path,options)
}
// jsonc 读
export const readJsonc = (path,options = {encoding:'utf8', flag:'r'}) => {
    if(!/.json$/.test(path)){
        throw new Error(`readJsonc :: 文件格式错误！ path = ${path}`)
    }
    const str = readFileSync(path,{encoding:'utf8', flag:'r'});
    return jsonc.parse(str);
}

export const writeJson = (path,data,options) => {
    if(!/.json$/.test(path)){
        throw new Error(`writeJson :: 文件格式错误！ path = ${path}`)
    }
    writeJSONSync(path,data,options)
}

export const writeJsonc = (path,data,options) => {
    if(!/.json$/.test(path)){
        throw new Error(`writeJsonc :: 文件格式错误！ path = ${path}`)
    }
    const s = jsonc.stringify(data);
    outputFileSync(path,s,options)
}

// config toml 文件读写
export class Config {
    constructor(basePath){
        this.basePath = basePath;
    }
    basePath = '';

    getPath(path){
        return this.basePath ? `${this.basePath}/path` : path;
    }
    // 读配置文件
    read(path,options){
        const p = this.getPath(path);
        return readToml(path,options)
    }
    // 写配置文件
}

// 生成入口文件

// 生成多入口文件

// 生成入口文件数据文件